package com.itheima.interceptor;

import com.itheima.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
@Component
@Slf4j
public class TokenInteceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 1 获取url
        String url = request.getRequestURL().toString();
        if (url.contains("adminlogin")){
            log.info("管理端登录，走过滤器去啦。。。。。");
        }
        // 2 判断是不是登录请求，如果是登录，直接放行
        if (url.contains("login")){
            return true;
        }

        // 3 获取token
        String token = request.getHeader("token");
        // 4 判断是否存在
        if (null == token || token.length() == 0){
            log.error("获取到jwt令牌为空, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        // 5 解析token

        Claims claims =null;
        try {
           claims = JwtUtils.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("解析令牌失败, 返回错误结果");
            response.setStatus(HttpStatus.SC_UNAUTHORIZED);
            return false;
        }
        Integer userId = (Integer) claims.get("id");
        log.info("设置当前线程变量");
        log.info("请求通过，拦截放行");
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("清除当前线程变量");
    }
}
